package com.mh.study.springcloud.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

import static java.util.Optional.ofNullable;

/**
 * 声明为bean，就会注册到gateway的全局过滤器中
 *
 * @author meng.han
 * @since 2022-03-18
 */
@Component
public class BlackListFilter implements GlobalFilter, Ordered {

    private static final List<String> BLACK_LIST = new ArrayList<>();

    static {
        BLACK_LIST.add("0:0:0:0:0:0:0:1");
    }

    /**
     * 过滤器核心方法
     *
     * @param exchange 封装了request和response对象的上下文
     * @param chain    网关过滤器链（包含全局过滤器和单路由过滤器）
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String clientIp = ofNullable(request.getRemoteAddress()).map(InetSocketAddress::getHostString).orElse(null);
        if (BLACK_LIST.contains(clientIp)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            String data = "Request be denied!";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
